<?php
/**
 * @property int $id
 * @property string $filename
 * @property string $path
 * @property string $title
 * @property string $description
 * @property string $created_at
 */
class Image extends ActiveRecord
{
	public $image;

	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return 'image';
	}

	public function attributeLabels()
	{
		return array(
			'filename' => 'Имя файла',
			'title' => 'Название',
			'description' => 'Описание',
			'created_at' => 'Дата',
			'image' => 'Файл'
		);
	}

	public function relations()
	{
		return array(
			'imageToArticle' => array(self::HAS_MANY, 'ImageToArticle', 'image_id'),
		);
	}

	public function rules()
	{
		return array(
			array('title, description, created_at', 'required'),
			array('id, title, description, created_at, image', 'safe'),
			array('image', 'file', 'types'=>'jpg, jpeg, gif, png'),
		);
	}

	public function search()
	{
		$criteria = new CDbCriteria;
		$criteria->compare('id',$this->id);
		$criteria->compare('filename',$this->filename, true);
		$criteria->compare('path',$this->path, true);
		$criteria->compare('title',$this->title, true);
		$criteria->compare('description',$this->description, true);
		if (!empty ($this->created_at)) {
			$criteria->compare('created_at', Yii::app()->format->dateHumanToNormal($this->created_at));
		}
		return new CActiveDataProvider('Image', array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'id DESC',
			),
		));
	}

	/**
	 * @return string
	 */
	public function calcDynamicPath($isCreate = true)
	{
		$path =  '/' . date('Y') . '/' . date('m');
		if ($isCreate && !is_dir($path)) {
			mkdir($path, 0777, true);
		}
		return $path;
	}
}